﻿using HCDV.HCSP;
using hcrainMvc.Controllers;
using hrainwebbase.ashx.spfunction;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace hcrainMvc.ashx.ywfunction
{
    public static class ywfunction
    {
        /// <summary>
        /// 根据基地ID，品种ID 要取的数据 获取贴码列表
        /// </summary>
        /// <param name="gjid"></param>
        /// <param name="spid"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<codeinfo> GetOutCodeList(string gjid, string spid, double count)
        {
            var codelist = new List<codeinfo>();
            DataTable dt = null;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format("select * from yw_baseinfo where type=20171015  and  maintype=20171015 and fv1='{0}' and fv3='{1}' order by dataaddtime asc",
                    gjid, spid));
            }
            //还要取的数据
            double need = count;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (need > 0)
                    {
                        var store = double.Parse(dr["nv5"].ToString());//还有
                        if (store >= need)//足够
                        {
                            codelist.Add(new codeinfo
                            {
                                startCode = dr["fv5"].ToString(),
                                endCode = simplefunction.getCodeSet0(dr["fv7"].ToString().Replace("hcrain", ""), ((double.Parse(dr["nv1"].ToString()) + need) - 1).ToString(), dr["fv5"].ToString().Length),
                                codeString = dr["fv7"].ToString(),
                                startNum = double.Parse(dr["nv1"].ToString()),
                                endNum = ((double.Parse(dr["nv1"].ToString()) + need) - 1),
                                codeCount = need
                            });
                            need = 0;
                            break;
                        }
                        else//不足够
                        {
                            codelist.Add(new codeinfo
                            {
                                startCode = dr["fv5"].ToString(),
                                endCode = dr["fv6"].ToString(),
                                codeString = dr["fv7"].ToString(),
                                startNum = double.Parse(dr["nv1"].ToString()),
                                endNum = double.Parse(dr["nv3"].ToString()),
                                codeCount = store
                            });
                            need = need - store;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

            }
            codelist.Add(new codeinfo { });
            codelist.Add(new codeinfo { });
            return codelist;
        }
        /// <summary>
        /// 格式化
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static codeinfo ReSetCodeInfo(codeinfo code)
        {
            var infoStart = simplefunction.hcrainFunction_getCodeNum(code.startCode);
            var infoEnd = simplefunction.hcrainFunction_getCodeNum(code.endCode);
            code.codeString = infoStart[0];
            code.startNum = double.Parse(infoStart[1]);
            code.endcodeString = infoEnd[0];
            code.endNum = double.Parse(infoEnd[1]);
            if (code.startCode == "" || code.endCode == "" || code.startCode == null || code.endCode == null) code.codeCount = 0;
            else code.codeCount = (code.endNum - code.startNum + 1);
            code.NumLenth = double.Parse(infoStart[2]);
            return code;
        }

        /// <summary>
        /// 出库处理
        /// </summary>
        /// <param name="codelist"></param>
        /// <returns></returns>
        public static string PostOutCodeListIsOk(List<codeinfo> codelist)
        {

            //List<codeinfo> codeinfolist = new List<codeinfo>();
            foreach (var code in codelist)
            {
                if (code.startCode == null && code.endCode == null) continue;
                if (code.startCode == "" && code.endCode == "") continue;
                if (code.startCode == null || code.endCode == null || code.startCode.Length != code.endCode.Length)
                {
                    return code.startCode + "与" + code.endCode + " 长度不一致!";
                }
                //格式化
                var code2 = ReSetCodeInfo(code);

                #region 这里不再分析是有效了，提交前已经处理了一次

                ////同一个号段
                //if (code2.endcodeString != code2.codeString)
                //    return code.startCode + "与" + code.endCode + " 不是同一个号段噢!";
                ////数值结束的要是数值
                //if (code.startCode.Length == code2.codeString.Length)
                //    return code.startCode + "与" + code.endCode + " 号段应该以数值结尾!";

                ////结束数值>=开始
                //if (code2.startNum > code2.endNum)
                //    return code.startCode + "与" + code.endCode + " 结束码应该大于等于开始码!";

                ////在库内
                ////   hcdoselbyPost("id,fv5,fv6", "yw_baseinfo", "type=20171015 and  fv7='" + $("#ffv7").val() + "' and ((nv1<=" + $("#fnv1").val() + " and nv3>=" + $("#fnv1").val() + ") or  (nv1<=" + $("#fnv3").val() + " and nv3>=" + $("#fnv3").val() + ") )  " + addwhere,
                //DataTable dt = null;
                //using (dbsimple db = new dbsimple())
                //{
                //    dt = db.Query(string.Format("select id from yw_baseinfo where type=20171015  and  maintype=20171015 and fv7='{0}' and (nv1<={1} and nv3>={1}) and  (nv1<={2} and nv3>={2}) order by dataaddtime asc",
                //        code2.codeString, code2.startNum, code2.endNum));
                //    if (dt == null || dt.Rows.Count == 0)
                //        return code.startCode + "-" + code.endCode + " 不在库内!";
                //}
                ////是否有记录了
                //var re = codeinfolist.FirstOrDefault(m =>
                //    m.codeString == code2.codeString
                //    && ((m.startNum <= code2.startNum && code2.startNum <= m.endNum) || (m.startNum <= code2.endNum && code2.endNum <= m.endNum))
                //    );
                //if (re != null)
                //{
                //    return re.startCode + "--" + code.startCode + " 的两个段号重复了!";
                //}
                //codeinfolist.Add(code2);
                #endregion

                #region 出库处理
                DataTable dt = null;
                using (dbsimple db = new dbsimple())
                {
                    if (string.IsNullOrEmpty(code2.codeString)) dt = db.Query(string.Format("select * from yw_baseinfo where type=20171015  and  maintype=20171015 and( fv7='' or fv7 is null) and (nv1<={1} and nv3>={1}) and  (nv1<={2} and nv3>={2}) and nv2={3}",
                        code2.codeString, code2.startNum, code2.endNum, code2.NumLenth));
                    else
                        dt = db.Query(string.Format("select * from yw_baseinfo where type=20171015  and  maintype=20171015 and fv7='{0}' and (nv1<={1} and nv3>={1}) and  (nv1<={2} and nv3>={2}) and nv2={3}",
                        code2.codeString, code2.startNum, code2.endNum, code2.NumLenth));
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        //以开始号出库
                        if (code2.startNum == double.Parse(dt.Rows[0]["nv1"].ToString()))
                        {
                            //部分出库--更新段号
                            if (code2.endNum < double.Parse(dt.Rows[0]["nv3"].ToString()))
                            {
                                //fv5开始号
                                //Fv6结束号
                                //Fv7 非数值部分',
                                //Nv1  开始号 '数值',
                                //Nv2 开始号'数值长度',
                                //Nv3  结束号 '数值',
                                //Nv4 结束号'数值长度',
                                //Nv5 数量
                                db.exe(string.Format("update yw_baseinfo set fv5 ='{0}',nv1={1},nv5={2}  where id={3}",
                                    simplefunction.getCodeSet0(dt.Rows[0]["fv7"].ToString(), (code2.endNum + 1).ToString(), code2.startCode.Length),
                                    code2.endNum + 1, //开始号数值
                                    double.Parse(dt.Rows[0]["nv3"].ToString()) - code2.endNum,//还有
                                    dt.Rows[0]["id"].ToString()
                                    ));
                            }
                            else//全部出库
                            {
                                db.exe(string.Format("delete from  yw_baseinfo where id={0}", dt.Rows[0]["id"].ToString()));
                            }

                        }
                        else//以中间开始出库
                        {
                            //后面全部出库--更新段号
                            if (code2.endNum >= double.Parse(dt.Rows[0]["nv3"].ToString()))
                            {
                                db.exe(string.Format("update yw_baseinfo set fv6 ='{0}',nv3={1},nv5={2}  where id={3}",
                                    simplefunction.getCodeSet0(dt.Rows[0]["fv7"].ToString(), (code2.startNum - 1).ToString(), code2.startCode.Length),
                                    code2.startNum - 1, //结束号数值
                                     code2.startNum - double.Parse(dt.Rows[0]["nv1"].ToString()),//还有
                                    dt.Rows[0]["id"].ToString()
                                    ));
                            }
                            else//只出中间一段
                            {
                                //将原有的更新结束部分

                                //fv5开始号
                                //Fv6结束号
                                //Fv7 非数值部分',
                                //Nv1  开始号 '数值',
                                //Nv2 开始号'数值长度',
                                //Nv3  结束号 '数值',
                                //Nv4 结束号'数值长度',
                                //Nv5 数量
                                db.exe(string.Format("update yw_baseinfo set fv6 ='{0}',nv3={1},nv5={2}  where id={3}",
                                    simplefunction.getCodeSet0(dt.Rows[0]["fv7"].ToString(), (code2.startNum - 1).ToString(), code2.startCode.Length),
                                    code2.startNum - 1, //结束号数值
                                     code2.startNum - double.Parse(dt.Rows[0]["nv1"].ToString()),//还有
                                    dt.Rows[0]["id"].ToString()
                                    ));
                                //插入后面部分
                                DataRow drnew = dt.Rows[0];
                                Hashtable allinfo = new Hashtable();
                                allinfo.Add("tablename", "yw_baseinfo");
                                allinfo.Add("ftype", dt.Rows[0]["type"].ToString());
                                allinfo.Add("ftypename", dt.Rows[0]["typename"].ToString());
                                allinfo.Add("fmaintype", dt.Rows[0]["maintype"].ToString());
                                allinfo.Add("ffv1", dt.Rows[0]["fv1"].ToString());
                                allinfo.Add("ffv2", dt.Rows[0]["fv2"].ToString());
                                allinfo.Add("ffv3", dt.Rows[0]["fv3"].ToString());
                                allinfo.Add("ffv4", dt.Rows[0]["fv4"].ToString());
                                allinfo.Add("ffv5", simplefunction.getCodeSet0(dt.Rows[0]["fv7"].ToString(), (code2.endNum + 1).ToString(), code2.startCode.Length));//
                                allinfo.Add("ffv6", dt.Rows[0]["fv6"].ToString());
                                allinfo.Add("ffv7", dt.Rows[0]["fv7"].ToString());
                                allinfo.Add("fnv1", (code2.endNum + 1).ToString());//
                                allinfo.Add("fnv2", dt.Rows[0]["nv2"].ToString());
                                allinfo.Add("fnv3", dt.Rows[0]["nv3"].ToString());
                                allinfo.Add("fnv4", dt.Rows[0]["nv4"].ToString());
                                allinfo.Add("fnv5", double.Parse(dt.Rows[0]["nv3"].ToString()) - code2.endNum);// 结束号 '数值'-code2.endNum


                                allinfo.Add("fdataadduserid", dt.Rows[0]["dataadduserid"].ToString());
                                allinfo.Add("fdatabranchid", dt.Rows[0]["databranchid"].ToString());
                                allinfo.Add("fdatadepid", dt.Rows[0]["datadepid"].ToString());
                                allinfo.Add("fdatadepname", dt.Rows[0]["datadepname"].ToString());
                                allinfo.Add("fdatabranchname", dt.Rows[0]["databranchname"].ToString());
                                allinfo.Add("fdataaddusername", dt.Rows[0]["dataaddusername"].ToString());
                                allinfo.Add("fdataaddtime", dt.Rows[0]["dataaddtime"].ToString());

                                string erinfo;
                                bool re = ObjIUD.insertInfo(allinfo, out erinfo);


                            }
                        }

                    }
                }

                #endregion
            }

            return "1";
        }
    }
}